from pymongo import UpdateOne

from zc_core.client.mongo_client import Mongo
from zc_core.util.common import parse_time, parse_number
from zc_core.util.encrypt_util import md5

mongo = Mongo()


def compare(sku_id):
    update_bulk = list()
    order_list = mongo.list('order_2020', query={'orderTime': {'$gte': parse_time('2020-06-25 0:00:00')}})
    for order in order_list:
        _id = order.get('_id')
        order_user = order.get('orderUser')
        if order_user and '*' not in order_user:
            update_bulk.append(UpdateOne({'_id': _id}, {'$set': {
                '_id': _id,
                'orderUser': None,
                'orderDept': order_user,
                'deptId': md5(order_user),
                'fix': '20200703',
            }}, upsert=False))

    print(len(update_bulk))
    mongo.bulk_write('order_2020', update_bulk)
    print('任务完成~')


def fix_order_item(year_month):
    update_bulk = list()
    order_list = mongo.list('order_item_{}'.format(year_month), query={'orderTime': {'$gte': parse_time('2020-06-25 0:00:00')}})
    for order in order_list:
        _id = order.get('_id')
        order_user = order.get('orderUser')
        if '*' not in order_user:
            update_bulk.append(UpdateOne({'_id': _id}, {'$set': {
                '_id': _id,
                'orderUser': None,
                'orderDept': order_user,
                'deptId': md5(order_user),
                'fix': '20200703',
            }}, upsert=False))

    print(len(update_bulk))
    mongo.bulk_write('order_item_{}'.format(year_month), update_bulk)
    print('任务完成~')


if __name__ == '__main__':
    batch_no = 20201103
    sku_list = mongo.list('sku_{}'.format(batch_no), fields={'_id': 1, 'salePrice': 1})
    print('skus: {}'.format(len(sku_list)))
    item_list = mongo.list('data_{}'.format(batch_no), fields={'_id': 1, 'salePrice': 1})
    print('datas: {}'.format(len(item_list)))

    item_map = dict()
    for item in item_list:
        item_map[item.get('_id')] = item.get('salePrice')

    for sku in sku_list:
        _id = sku.get('_id')
        sku_price = parse_number(sku.get('salePrice'))
        data_price = item_map.get(_id)
        # if not sku_price:
        #     print('no sku: sku=%s' % _id)
        #     continue
        # if not data_price:
        #     print('no data: sku=%s' % _id)
        #     continue
        if data_price and sku_price and sku_price != data_price:
            print('--> not equals: sku=%s, sku=%s, data=%s' % (_id, sku_price, data_price))
